<template>
  <div class="app-container">

    <CustomContent>
      <template v-slot:body>
        <div id="mmv-page" v-loading="loading">
          <MmvTitle title="车型信息"></MmvTitle>
          <el-form size="mini" label-width="130px" ref="form">

            <el-row :gutter="15">
              <el-col :span="12">
                <el-form-item label="选择车型" required>
<!--                  <el-input :value="modelInfo" readonly style="width:100%" placeholder="品牌车系车型" ></el-input>-->
                  {{modelInfo}}
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="车辆级别" prop="operatingClassification">
                  <el-select style="width:100%" filterable remote v-model="operatingClassification" disabled placeholder="请选择车辆级别">
                    <el-option v-for="item in rankList" :key="item.rankId" :value="item.rankId" :label="item.rankName">
                      {{ item.rankName }}
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>



            <el-row :gutter="15">
              <el-col :span="24">
                <el-form-item label="列表图片" prop="upcoverImage">
                  <MmvUploadImage :autoCropWidth="235" :autoCropHeight="118" ref="coverImage" :showDelete="false" :size="1"></MmvUploadImage>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="15">
              <el-col :span="24">
                <el-form-item label="详情图片" prop="detailsImage">
                  <MmvUploadImage  ref="detailsImage" :more="true" :size="1" :autoCropWidth="375" :showDelete="false" :autoCropHeight="256"></MmvUploadImage>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="15">
              <el-col :span="24">
                <el-form-item label="车型配置" prop="modelConfig">
                  <div>
                    <el-checkbox-group v-model="modelConfig" disabled>
                      <el-checkbox v-for="dict in dict.type.car_model_config_list" :key="dict.value" :label="dict.value">{{ dict.label }}</el-checkbox>
                    </el-checkbox-group>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="15">
              <el-col :span="24">
                <el-form-item label="车型标签" prop="label" >
                  <el-checkbox-group v-model="label" disabled>
                    <el-checkbox v-for="dict in dict.type.car_model_label" :key="dict.value" :label="dict.value"> {{ dict.label }}</el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="15">
              <el-col :span="12">
                <el-form-item label="车辆押金" prop="deposit">
                  {{deposit}}
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="违章押金" prop="illegalDeposit">
                  {{tenantConfig.illegalDeposit}}
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>

          <MmvTitle title="价格配置"></MmvTitle>
          <el-row :gutter="30">
            <el-col :span="12">
              <el-table :data="holidayEffectiveList" border max-height="420">
                <el-table-column label="价格名称"  align="center" prop="dateName" min-width="120" show-overflow-tooltip > </el-table-column>
                <el-table-column label="生效日期"  align="center" prop="datepicker" min-width="120" show-overflow-tooltip>
                  <template slot-scope="scope">
                    <span v-if="scope.row.type=='weeksPrice'">周内（1-4）</span>
                    <span v-else-if="scope.row.type=='weekendPrice'">周末（5-7）</span>
                    <span v-else>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}至{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="单日价格（元）"  align="center" prop="value" min-width="120" show-overflow-tooltip >
                  <template slot-scope="scope">
                    {{scope.row.value}}元
                  </template>
                </el-table-column>
              </el-table>
              <template v-if="holidayLapseList.length>0">
                <div> 失效价格
                  <el-button type="text" size="mini" @click="retract=!retract">{{retract?'收起':'展开'}}</el-button>
                </div>
                <el-table :data="holidayLapseList" border max-height="420" v-show="retract">
                  <el-table-column label="价格名称"  align="center" prop="dateName" min-width="120" show-overflow-tooltip > </el-table-column>
                  <el-table-column label="生效日期"  align="center" prop="datepicker" min-width="120" show-overflow-tooltip>
                    <template slot-scope="scope">
                      <span v-if="scope.row.type=='weeksPrice'">周内（1-4）</span>
                      <span v-else-if="scope.row.type=='weekendPrice'">周末（5-7）</span>
                      <span v-else>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}至{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="单日价格（元）"  align="center" prop="value" min-width="120" show-overflow-tooltip >
                    <template slot-scope="scope">
                      {{scope.row.value}}元
                    </template>
                  </el-table-column>
                </el-table>
              </template>
            </el-col>


            <el-col :span="12">
              <el-calendar v-model="value" style="max-height: 520px">
                <template slot="dateCell"
                          slot-scope="{date, data}">
                  <div class="rili-wrap"
                       :class="{'is-selected':data.isSelected,aaaaaa:isEditaaaaaa(date)}"
                       style="padding:8px;height: 100%;">
                    <div class="rili-day">{{ data.day.split('-').slice(1).join('-') }}</div>
                    <div class="rili-price-wrap">
                      <div>￥{{ superMmv(date, rilijiage[date.getDay()]) }}</div>
                    </div>
                  </div>
                </template>
              </el-calendar>
            </el-col>
          </el-row>



          <MmvTitle title="保险价格"></MmvTitle>
          <el-row :gutter="15">
            <el-col :span="24">
              <el-table :data="chargeInsureList" border  ref="insureTable">
                <el-table-column label="保险名称" align="center" prop="chargeItemsName" min-width="120" show-overflow-tooltip />
                <el-table-column label="简介" align="center" prop="remark" min-width="120" show-overflow-tooltip />
                <el-table-column label="价格" align="center" prop="unitPrice">
                  <template slot-scope="{ row }">
                    {{row.unitPrice}} 元/天
                  </template>
                </el-table-column>
                <el-table-column label="收费天数上限" align="center" min-width="120" prop="upperLimitOfNumber">
                  <template slot-scope="scope">
                    <span>{{ scope.row.upperLimitOfNumber&&scope.row.upperLimitOfNumber>=0 ? scope.row.upperLimitOfNumber : '无上限' }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="是否可选" align="center" min-width="80">
                  <template slot-scope="scope">
                    <span>{{ scope.row.isOptional | isOptional }}</span>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>

          <MmvTitle title="其他收费项"></MmvTitle>
          <el-row :gutter="15">
            <el-col :span="24">
              <el-table :data="chargeItemsList" border ref="itemTable" >
                <el-table-column label="收费项名称" align="center" prop="chargeItemsName" min-width="120" show-overflow-tooltip />
                <el-table-column label="收费项说明" align="center" prop="remark" min-width="120" show-overflow-tooltip />
                <el-table-column label="价格" align="center" prop="unitPrice">
                  <template slot-scope="{ row }">
                    {{row.unitPrice}} 元/<dict-tag style="display: inline-block" :options="dict.type.charge_type" :value="row.chargeItemsType"/>
                  </template>
                </el-table-column>
                <el-table-column label="收费次数上限" align="center" min-width="120" prop="upperLimitOfNumber">
                  <template slot-scope="scope">
                    <span>{{ scope.row.upperLimitOfNumber&&scope.row.upperLimitOfNumber>=0 ? scope.row.upperLimitOfNumber : '无上限' }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="收费金额上限" align="center" min-width="120" prop="upperLimitOfAmount">
                  <template slot-scope="scope">
                    <span>{{ scope.row.upperLimitOfAmount&&scope.row.upperLimitOfAmount>=0 ? scope.row.upperLimitOfAmount : '无上限' }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="是否可选" align="center" min-width="80">
                  <template slot-scope="scope">
                    <span>{{ scope.row.isOptional | isOptional }}</span>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
          <template v-if="tenantConfig.nightServiceFee == 1">
            <MmvTitle title="夜间服务费"></MmvTitle>
            <el-row :gutter="15">
              <el-col :span="24">
                <el-descriptions direction="vertical" :column="4" border>
                  <el-descriptions-item label="时间" :contentStyle="{'text-align': 'center'}" :labelStyle="{'text-align': 'center'}">{{ tenantConfig.nightServiceFeeStart }}至{{ tenantConfig.nightServiceFeeEnd }}</el-descriptions-item>
                  <el-descriptions-item label="价格（元/次）" :contentStyle="{'text-align': 'center'}" :labelStyle="{'text-align': 'center'}">{{ tenantConfig.nightServiceFeePrice }}元/次</el-descriptions-item>
                  <el-descriptions-item label="说明" :span="2" :contentStyle="{'text-align': 'center'}" :labelStyle="{'text-align': 'center'}">{{ tenantConfig.nightServiceFeeRemark }}</el-descriptions-item>
                </el-descriptions>
              </el-col>
            </el-row>
          </template>

        </div>
      </template>
      <template v-slot:footer>
        <div class="footer">
          <el-button type="info" plain @click.native="close">关闭</el-button>
        </div>
      </template>
    </CustomContent>
  </div>
</template>

<script>
import MmvTitle from '@/components/MmvUI/MmvTitle.vue'
import * as planApi from "@/api/plan/plan";
import forEach from 'lodash/forEach';
import MmvTable from './components/mmv-table.vue'
import MmvUploadImage from '../components/mmv-upload-image.vue'
import * as Utils from '@/utils'
import {tenantlist} from "@/api";
import CustomContent from "@/components/custom/content";

export default {
  components: {
    MmvTitle,
    MmvTable,
    MmvUploadImage,
    CustomContent,
  },
  dicts: [
    'charge_type',
    'car_model_list_classification',
    'car_model_luxury_classification',
    'car_model_label',
    'operating_classification',
    'business_classification',
    'car_model_config_list', 'car_status'
  ],
  data() {
    return {
      rankList: [],
      modelList: [],
      // 总条数
      total: 0,
      drawerFlag: false,
      retract: false,
      addPlanLoading: false,
      direction: 'rtl',
      tenantId: '',
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        modelId: null,
        carNo: null,
      },
      modeltotal: 0,
      modelloading: false,
      deposit: 0,
      weeksPrice: 0, // 周内价格
      weekendPrice: 0, // 周末价格
      //
      prevEdit: null,
      nowPrice: 0,
      nowEdit: null,
      loading: false,
      showchexing: false,
      title: '',
      planName: '', // 车价名称
      //
      configurationId: '', // 品牌车系车型
      modelId: '',
      modelName: '',
      modelInfo: '',
      upcoverImage: '',
      detailsImage: [],
      modelConfig: [],
      //
      label: [],
      operatingClassification: "",
      //
      isSetMeal: 2, // 是否需要套餐车价
      // 是否显示弹出层
      open: false,
      openkehu: false, // 客户选择弹窗
      value: new Date(),
      list: [{
        mondayPrice: 0,
        tuesdayPrice: 0,
        wednesdayPrice: 0,
        thursdayPrice: 0,
        fridayPrice: 0,
        saturdayPrice: 0,
        sundayPrice: 0,
      }],
      checktable: [{}],
      checktableindex: 0,
      checklistteshutable: [{}],
      checklistteshutableindex: 0,
      radio: 0,
      chargeInsureList: [], // 保险项
      selectInsureIds: [], // 保险项ids
      chargeItemsList: [], // 收费项
      selectItemsIds: [], // 收费项ids
      configurationList: [], // 车型业务配置列表
      configurationquery: {
        pageNum: 1,
        pageSize: 10,
        modelName: null,
        configurationId: null
      },
      tenantConfig: {
        illegalDeposit: 0,
        pageSinightServiceFeeze: 2,
        nightServiceFeeStart: null,
        nightServiceFeeEnd: null,
        nightServiceFeePrice: null,
        nightServiceFeeRemark: null
      },
      // 节假日
      holidayList: [], // 节假日列表
      holidayEffectiveList: [], //有效节假日列表
      holidayLapseList: [], // 失效节假日列表
    }
  }, computed: {
    isEdit() {
      return !!this.form.planId;
    },
    rilijiage() {
      return {
        0: this.list[0].sundayPrice,
        1: this.list[0].mondayPrice,
        2: this.list[0].tuesdayPrice,
        3: this.list[0].wednesdayPrice,
        4: this.list[0].thursdayPrice,
        5: this.list[0].fridayPrice,
        6: this.list[0].saturdayPrice,
      }
    },
  },
  watch: {
    weeksPrice(val) {
      this.list[0].mondayPrice = val;
      this.list[0].tuesdayPrice = val;
      this.list[0].wednesdayPrice = val;
      this.list[0].thursdayPrice = val;
    },
    weekendPrice(val) {
      this.list[0].fridayPrice = val;
      this.list[0].saturdayPrice = val;
      this.list[0].sundayPrice = val;
    },
  },
  async mounted() {
    this.loading = true;
    await this.getTenantConfig(); // 获取租户配置
    this.loading = false;
    this.planId = this.$route.query.planId;
    if (this.planId) {
      console.log('走修改流程');
      await this.getData();
    }
    this.getrankList();
  },
  methods: {
    async getrankList() {

      if (this.planId) {
        console.log('走修改流程');
        tenantlist({tenantId: this.tenantId}).then(res => {
          this.rankList = res.data
        })
      } else {
        tenantlist().then(res => {
          this.rankList = res.data
        })
      }


    },

    /** 获取租户配置 */
    async getTenantConfig() {
      const result = await planApi.getTenantConfig();
      this.tenantConfig = result.data;
    },
    /** 日历价格显示计算器 */
    superMmv(date, price) {
      // 计算出的价格
      let _price = price;

      function mmv(value) {
        // return value;
        const _date = new Date(value);
        return new Date(_date.getFullYear(), _date.getMonth() + 1, _date.getDate()).getTime();
      }

      // 日历当前格子时间戳
      const time = mmv(date);
      // 遍历节假日数组
      require('lodash/forEach')(this.holidayList, val => {
        const start_time = mmv(val.startTime);
        const end_time = mmv(val.endTime);
        if (time <= end_time && time >= start_time && val.value!=null) {
          _price = val.value;
        }
      });
      return _price;
    },
    isEditaaaaaa(date) {
      function mmv(value) {
        // return value;
        const _date = new Date(value);
        return new Date(_date.getFullYear(), _date.getMonth() , _date.getDate()).getTime();
      }
      const time = mmv(date);
      // 遍历节假日数组
      const item = this.holidayList.find(val => {
        const start_time = mmv(val.startTime);
        const end_time = mmv(val.endTime);
        if (time <= end_time && time >= start_time) {
          return true
        }
      });
      return !!item
    },

    close() {
      // 关闭页面
      this.$router.go(-1)
      this.$store.dispatch('tagsView/delView', this.$route)
    },
    async getData() {
      this.loading = true;
      let holidayVoList=[];
      let itemsVoList=[];
      await planApi.getNewInfo(this.planId).then(response => {
        this.configurationId = response.data.configurationId;
        this.operatingClassification = response.data.operatingClassification;
        this.modelId = response.data.modelId;
        this.modelConfig = String(response.data.modelConfig).split(',');
        this.label = String(response.data.label).split(',');
        this.deposit = response.data.deposit;
        this.weeksPrice = response.data.weeksPrice;
        this.weekendPrice = response.data.weekendPrice;
        this.upcoverImage = response.data.upcoverImage;
        this.detailsImage = response.data.detailsImage;
        this.modelInfo = response.data.modelInfo;
        this.tenantId = response.data.tenantId;
        this.modelName = response.data.modelName
        holidayVoList = response.data.holidayVoList
        itemsVoList = response.data.itemsVoList
        //
        this.$refs.coverImage.previewToUrl(Utils.getImgUrl(response.data.upcoverImage));
        this.$refs.detailsImage.previewToUrl(String(response.data.detailsImage.map(val => {
          return Utils.getImgUrl(val);
        })));
        // 还原节假日/特殊日价格
        this.loading = false;
      });

      for(let item of itemsVoList){
        item.checked=false
        if(item.projectType===2){
          this.chargeInsureList.push(item)
        }else{
          this.chargeItemsList.push(item)
        }
      }

      this.holidayEffectiveList =[
        {
          dateName:"周内价格",
          type:"weeksPrice",
          dateType:0,
          value:this.weeksPrice,
        },{
          dateName:"周末价格",
          type:"weekendPrice",
          dateType:0,
          value:this.weekendPrice,
        }]
      forEach(holidayVoList, val => {
        this.holidayList.push({
          dateName:val.holidayName,
          dateType:val.holidayType,
          value:val.price,
          startTime:val.startTime,
          endTime:val.endTime,
        })
        if(val.validOrNot===1){
          this.holidayEffectiveList.push({
            dateName:val.holidayName,
            dateType:val.holidayType,
            value:val.price,
            startTime:val.startTime,
            endTime:val.endTime,
          })
        }else{
          this.holidayLapseList.push({
            dateName:val.holidayName,
            dateType:val.holidayType,
            value:val.price,
            startTime:val.startTime,
            endTime:val.endTime,
          })
        }

      });
    },
    /** */
  },
}
</script>

<style>
#mmv-page .next {
  background: #f5f5f5;
}

#mmv-page .prev {
  background: #f5f5f5;
}

#mmv-page .el-calendar-day {
  padding: 0;
}

#mmv-page .next .rili-price-wrap {
  display: flex;
  align-items: center;
  padding: 5px 5px 0;
  color: #999;
  font-weight: bold;
  font-size: 16px;
  text-align: center;
  justify-content: center;
  white-space: nowrap;
}
</style>

<style lang="scss" scoped>
#mmv-page {

::v-deep .el-calendar-table .el-calendar-day {
  height: 60px;
}

}
.rili {
  width: 100%;
  height: 100%;
  font-size: 12px;
}

.rili-wrap {
  position: relative;
}

.el-icon-refresh-left {
  position: absolute;
  top: 8px;
  right: 8px;
}

.aaaaaa {
  background: rgb(253, 226, 226);
}

.rili-day {
  color: #999;
}

.rili-price-wrap {
  display: flex;
  align-items: center;
  padding: 5px 5px 0;
  color: #409eff;
  font-weight: bold;
  font-size: 16px;
  text-align: center;
  justify-content: center;
  white-space: nowrap;

}
</style>
